package com.ruoyi.system.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/register")
public class SysRegisterController {
    @Autowired
    private ISysUserService userService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @PostMapping
    public AjaxResult register(@RequestBody SysUser user) {
        // 用户名唯一性校验
        if (!userService.checkUserNameUnique(user)) {
            return AjaxResult.error("用户名已存在");
        }
        // 密码加密
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        // 设置默认状态
        user.setStatus("0");
        // 保存用户
        int rows = userService.insertUser(user);
        if (rows > 0) {
            List<SysUserRole> list = new ArrayList<>();
            SysUserRole userRole = new SysUserRole();
            userRole.setRoleId(2L);
            userRole.setUserId(user.getUserId());
            list.add(userRole);
            sysUserRoleMapper.batchUserRole(list);
            return AjaxResult.success("注册成功");
        } else {
            return AjaxResult.error("注册失败");
        }
    }
} 